package com.heima.wemedia.filter;

import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @作者 itcast
 * @创建日期 2021/4/13 15:46
 **/
@WebFilter(urlPatterns = "/*",value = "wmTokenFilter")
@Component
@Slf4j
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 通过request对象获取请求头信息(userId)
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        // 2. 如果userId不为空 ，封装一个WmUser(登录用户) , 存入到ThreadLocal
        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)){
            WmUser user = new WmUser();
            user.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(user);
        }
        // 3. 放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
